<template>
  <div>

    <!--搜索卡片-->
    <el-card class="box-card" :body-style="{ padding: '10px',height:'30px'}">
      <el-form :inline="true" :model="searchInfo" ref="ruleForm" class="demo-form-inline">
        <el-form-item label="标题名" prop="infoName">
          <el-input size="small" v-model="searchInfo.infoName" placeholder="标题名" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="租房类型" prop="typeId">
          <el-select v-model="searchInfo.typeId" placeholder="请选择租房类型" clearable :style="{width: '100%'} "
                     size="medium">
            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="success" round size="small" @click="onSearch">查询</el-button>
          <el-button type="warning" round size="small" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="Button">

      <el-button size="small" type="primary" @click="addInfo" icon="el-icon-plus" plain>新增</el-button>
      <el-button size="small" type="danger" @click="deleteBatch" icon="el-icon-delete-solid" plain>批量删除</el-button>

    </div>

    <!--数据表格-->
    <el-table :data="tableData" style="width: 100%;" max-height="100%"
              @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="60"></el-table-column>
      <el-table-column prop="userId" label="用户" width="100"></el-table-column>
      <el-table-column prop="infoName" label="标题名" width="160"></el-table-column>
      <el-table-column prop="img" label="房间图片" width="200">
        <template slot-scope="scope">
          <el-image :src=" baseUrl + scope.row.img"
               alt="房间图片" style="width: 50px; height: auto;"
               :preview-src-list="[baseUrl + scope.row.img]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="房间描述" width="400"></el-table-column>
      <el-table-column prop="typeId" label="租房类型" width="120">
        <template slot-scope="scope">
          {{ getTypeName(scope.row.typeId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页查询-->

    <el-card class="box-card" :body-style="{ padding: '10px',height:'20px'}">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchInfo.pageNum"
        :page-sizes="[7, 12, 17, 22]"
        :page-size="searchInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total">
      </el-pagination>
    </el-card>


    <!--新增弹框-->
    <el-dialog :title="title" v-bind="$attrs" v-on="$listeners" @close="onClose" :visible.sync="editInfoDialog">
      <el-form ref="editInfo" :model="editInfo" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="标题名" prop="infoName">
          <el-input v-model="editInfo.infoName" placeholder="请输入标题名" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="img" required>
          <el-upload
            ref="img"
            class="upload-demo"
            action=""
            :auto-upload="false"
            :before-upload="imgBeforeUpload"
            :file-list="imgfileList"
            :limit="1"
            :on-change="handleChange"
          >
            <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="房间描述" prop="description">
          <el-input v-model="editInfo.description" type="textarea" placeholder="请输入房间描述"
                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="租房类型" prop="typeId">
          <el-select v-model="editInfo.typeId" placeholder="请选择租房类型" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="resetEditForm('editInfo')">取消</el-button>
        <el-button type="primary" @click="saveInfo('editInfo')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addInfo, delInfoBatch, delInfoById, editInfo, findAll, findTypeName} from "@/api/reservationInfo/info";
import {uploadPicture} from "@/api/upload";

export default {
  name: "ReservationInfo",
  data() {
    return {
      baseUrl: 'https://wanghao1234.oss-cn-hangzhou.aliyuncs.com/g8hms/',
      editInfoDialog: false,
      tableData: [],
      searchInfo: {  // 查询条件
        infoName: null,
        typeId: null,

        pageNum: 1,// 当前页面
        pageSize: 7,// 每页大小
      },

      editInfo: {
        userId: null,
        infoName: null,
        img: null,
        description: null,
        typeId: '',
      },
      total: 0,
      title: '添加信息',

      rules: {
        infoName: [{
          required: true,
          message: '请输入标题名',
          trigger: 'blur'
        }],
        description: [{
          required: true,
          message: '请输入房间描述',
          trigger: 'blur'
        }],
        typeId: [{
          required: true,
          message: '请选择租房类型',
          trigger: 'change'
        }],
        img: [{
          required: true,
          message: '请上传图片',
          trigger: 'change'
        }],
      },
      imgfileList: [],
      typeOptions: [],
      multipleSelection: [],
      selectedFile: null, // 用于存储选择的文件

    }
  },
  methods: {

    // 把选择的图片赋值给 editInfo.img
    handleChange(file, fileList) {
      this.selectedFile = file.raw; // 确保正确存储选择的文件对象
      this.editInfo.img = URL.createObjectURL(file.raw); // 将图片的本地地址赋值给 editInfo.img
    },

    uploadFile() {
      if (!this.selectedFile) {
        // 没有图片，直接 resolve，不上传图片
        return Promise.resolve();
      }
      const formData = new FormData();
      formData.append("file", this.selectedFile); // 将文件添加到 FormData
      return uploadPicture(formData).then((res) => {
        if (res.code === 20000) {
          this.editInfo.img = res.data; // 将上传后的图片路径赋值给 editInfo.img
          this.$message({
            message: "上传成功",
            type: "success",
          });
          return Promise.resolve(); // 返回一个 resolved 的 Promise
        } else {
          this.$message.error('图片上传失败');
          return Promise.reject(new Error('图片上传失败')); // 返回一个 rejected 的 Promise
        }
      }).catch(() => {
        this.$message.error('图片上传失败');
        return Promise.reject(new Error('图片上传失败')); // 返回一个 rejected 的 Promise
      });
    },

    onSearch() {
      this.findAll()
    },

    // 查询全部数据
    findAll() {
      findAll(this.searchInfo).then(res => {
        if (res.code === 20000) {
          this.tableData = res.data.list;
          this.total = res.data.total;
        }
      }).catch(error => {
        console.log('请求查询全部报错: ', error)
      })
    },

    findTypeName() {
      findTypeName().then(res => {
        if (res.code === 20000) {
          this.typeOptions = res.data.map(item => ({
            label: item.typeName,
            value: item.typeId,
          }));
        }
      }).catch(error => {
        console.log('请求查询租房类型报错: ', error)
      })
    },

    // 添加预约信息
    addInfo() {
      this.title = "添加信息"
      this.editInfoDialog = true
    },
    // 修改预约信息
    handleEdit(index, row) {
      this.title = "更新信息"
      // 使用 Object.assign 或者扩展运算符创建 row 的副本
      this.editInfo = {...row}; //
      this.editInfoDialog = true
    },

    // 添加/修改预约信息
    saveInfo(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.uploadFile().then(() => {
            if (this.title === "添加信息") {
              this.editInfo.userId = this.$store.getters.id;
              addInfo(this.editInfo).then(ret => {
                if (ret.code === 20000) {
                  this.$message({
                    type: 'success',
                    message: '添加成功!'
                  });
                }
                this.findAll();
                this.$refs[formName].resetFields();
                this.editInfoDialog = false;
              });
            } else {
              editInfo(this.editInfo).then(ret => {
                if (ret.code === 20000) {
                  this.$message({
                    type: 'success',
                    message: '修改成功!'
                  });
                }
                this.findAll();
                this.$refs[formName].resetFields();
                this.editInfoDialog = false;
              });
            }
          }).catch(() => {
            this.$message.error('请先上传图片');
          });
        }
      })
    },

    // 删除
    handleDelete(index, row) {
      console.log(row.id)
      this.$confirm('是否确认删除编号为"' + row.id + '"的信息？', '删除预约信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delInfoById(row.id).then(ret => {
          console.log(row.id);
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功！',
              duration: 1000,
            });
            this.findAll();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 批量删除
    deleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择要删除的数据'
        });
      } else {
        this.$confirm('是否确认删除用户编号为"[' + this.multipleSelection + ']"的单位？', '批量删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delInfoBatch({
            ids: this.multipleSelection.join(',')
          }).then(ret => {
            // console.log(ret);
            if (ret.code === 20000) {
              this.$message({
                type: 'success',
                message: '删除成功！',
                duration: 1000
              })
              this.findAll();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },


    resetForm(formName) {  // 重置
      this.$refs[formName].resetFields();
      this.findAll();
    },
    onClose() {
      this.resetEditForm('editInfo'); // 第二次编辑会覆盖问题
    },

    resetEditForm(formName) { // 重置编辑表单
      this.editInfo = {
        userId: null,
        infoName: null,
        img: null,
        description: null,
        typeId: null,
      }
      this.$refs[formName].resetFields(); // 重置规则
      this.editInfoDialog = false
    },


    imgBeforeUpload(file) { // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
      let isRightSize = file.size / 1024 / 1024 < 10  // 上传图片大小小于10MB
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },


    // 批量删除存的编号数组
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (const index in val) {
        this.multipleSelection.push(val[index].id); // 取出val中的id
      }
    },

    // 分页查询配置
    handleSizeChange(val) { // 处理页面大小改变时触发
      this.searchInfo.pageSize = val;
      this.findAll()
    },
    handleCurrentChange(val) {// 当前页码改变时触发
      this.searchInfo.pageNum = val;
      this.findAll()
    },

    getTypeName(typeId) {
      const option = this.typeOptions.find(option => option.value === typeId);
      return option ? option.label : '未知';
    },

  },

  created() {
    this.findAll()
    this.findTypeName()
  },
}
</script>

<style scoped lang="scss">
.box-card {
  width: 100%;
  margin-top: 1px;
  height: 55px;
}

.Button {
  margin-left: 10px;
  margin-top: 10px;
}
</style>
